#include <bits/stdc++.h>
using namespace std;
int t, n;
char str[5];
const int N = 20005;
int par[N], dist[N];
int find(int x) {
  if (x == par[x]) return x;
  int fx = find(par[x]);  // 这行不能写在更新dist之后
  dist[x] = dist[x] + dist[par[x]];
  return par[x] = fx;
}
void unite(int x, int y) {
  int fx = find(x), fy = find(y);
  if (fx == fy) return;
  par[fx] = y;
  dist[fx] = dist[x];
  dist[x] = abs(x - y) % 1000;
}
int main() {
  int i, j, k, x, y;
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 0; i <= n; ++i) {
      par[i] = i;
      dist[i] = 0;
    }
    while (cin >> str) {
      if (*str == 'O')
        break;
      else if (*str == 'E') {
        cin >> x;
        find(x);
        cout << dist[x] << '\n';
      } else {
        cin >> x >> y;
        unite(x, y);
      }
    }
  }
}
